/*
 * Copyright (C) 2020 唐家林
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package server

import (
	"fmt"
	"github.com/gorilla/mux"
	"github.com/sudot/yapi-tools/internal/assets"
	"github.com/sudot/yapi-tools/internal/controller"
	"github.com/sudot/yapi-tools/internal/logger"
	"net/http"
	"net/url"
)

var ApiRouter *mux.Router

const (
	GET    = "GET"
	POST   = "POST"
	PUT    = "PUT"
	DELETE = "DELETE"
)

func RunServer(port int) {
	logger.Infof("服务启动完毕。端口：%d。若要指定端口，请使用 -p <port> 指令\n", port)
	router := mux.NewRouter()
	// 接口
	ApiRouter = router.PathPrefix("/api").Subrouter()
	ApiRouter.HandleFunc("/interfaces", controller.InterfacesHandler).Methods(GET)
	ApiRouter.HandleFunc("/interfaces/{id}", controller.InterfaceHandler).Methods(GET)
	ApiRouter.HandleFunc("/interfaces", controller.InterfaceSaveHandler).Methods(POST)
	ApiRouter.HandleFunc("/interfaces/{id}", controller.InterfaceDeleteHandler).Methods(DELETE)
	// 静态页面(路径范围越大的要放在越后面）
	router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 解决 go-bindata 在 windows 下打包多个目录，使用 -prefix 参数生成的文件编译报错
		r.URL, _ = url.Parse("/web" + r.URL.EscapedPath())
		http.FileServer(assets.AssetFile()).ServeHTTP(w, r)
	})
	http.Handle("/", router)
	_ = http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
